﻿#!/usr/bin/env python3


def main():
    '''
iterable -
*.iterable object, 也即iterator的container, 带有__iter__()方法. __iter__()返回iterator object. __iter__()可以返回generator iterator.
*.iterator带有__iter__(), 返回自己, 和__next__()方法, 返回next item, 或者到尾抛StopIteration exception.

generator 和generator iterator -
generator是返回generator iterator的function.
generator iterator使用yield语句构成的iterator.

generator expr -
comprehension expr的一种,以小括号包围, 可以生成list.

    '''
    print(main.__doc__)
    print('-'*21)
    fib = Fibs()
    print([x for x in fib])

    print('-'*21)
    fib = Fibs2()
    print([x for x in fib])

    print('-'*21)
    sq = (x**2 for x in range(10))   
    print(sq.__next__())
    print(sq.__next__())
    print(list(sq))

class Fibs:
    '''
以自身为iterator的iterable.    
    '''
    def __init__(self):
        self.a = 0
        self.b = 1
    def __iter__(self):
        return self        
    def __next__(self):
        self.a, self.b = self.b, self.a + self.b
        if(self.a>10):
            raise StopIteration
        return self.a

class Fibs2:
    '''
以自身为iterator的iterable.    
    '''
    def __iter__(self):
        a = 0
        b = 1
        while a<10:
            c = b + a
            a = b
            b = c
            yield c

if __name__=='__main__':
    main()
